package com.hwtx.form.util;

import lombok.extern.slf4j.Slf4j;

import java.text.DecimalFormat;

@Slf4j
public class NumberUtil {
    /*
     * HEX ：十六进制 Hexadecimal
     * DEC ：十进制 Decimal
     * OCT ：八进制 Octal
     * BIN ：二进制 Binary
     * */

    /**
     * 数字格式化
     *
     * @param src     src
     * @param pattern 名称统配符或正则
     * @return String
     */
    public static String format(Number src, String pattern) {
        if (null == src) {
            return "";
        }
        DecimalFormat df = new DecimalFormat(pattern);
        return df.format(src);
    }


    public static String byte2hex(byte[] bytes, String split) {
        return byte2hex(bytes, bytes.length, split);
    }

    public static String byte2hex(byte[] bytes, int len, String split) {
        return byte2hex(bytes, 0, len, split);
    }

    public static String byte2hex(byte[] bytes, int start, int len, String split) {
        StringBuilder builder = new StringBuilder();
        int size = 0;
        for (int i = start; i < start + len; i++) {
            size++;
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() < 2) {
                builder.append(0);
            }
            builder.append(hex);
            if (size < len && null != split) {
                builder.append(split);
            }
        }
        return builder.toString();
    }

    public static String byte2hex(byte[] bytes) {
        return byte2hex(bytes, null);
    }


}
